<?php
set_include_path($_SERVER['DOCUMENT_ROOT']);
include_once 'admin/includes/functions/admin-functions.php';
ini_set('display_errors',1);
ini_set('error_reporting',E_ALL ^ E_NOTICE ^ E_WARNING);
global  $CONFIG,$SMARTY,$DBobject;

echo "=> Cron started<br>";
$classTermObj = new ClassTermClass();
$enrol_obj = new Enrolment();

$devAdmin = "readysteadygokids@bccgmail.com";
$from = (string) $CONFIG->company->name;
$fromEmail = 'noreply@'. str_replace('www.', '', $GLOBALS['HTTP_HOST']);
$COMP = json_encode($CONFIG->company);
$SMARTY->assign('COMPANY', json_decode($COMP,TRUE));
$SMARTY->assign('DOMAIN', "http://" . $GLOBALS['HTTP_HOST']);

$events = array();
$membersEmailArr = array();
$membersPhoneArr = array();

$subject = "澳睿跑 (Ready Steady Go Kids) | 体验课程跟踪回访";
$weekday = date('l');
$day = date('Y-m-d');
$dateEmail = date('d F Y');

//Only at THEM
if($_SERVER['REMOTE_ADDR']=='150.101.230.130' && !empty($_REQUEST['date'])){
	$weekday = date('l', strtotime($_REQUEST['date']));
	$day = date('Y-m-d', strtotime($_REQUEST['date']));
	$dateEmail = date('d F Y', strtotime($_REQUEST['date']));
}

echo "=> Trial follow-up: $weekday - $day  <br>";


//Get "Trial follow up" message
$sql = "SELECT email_additional_content FROM tbl_email_additional WHERE email_additional_deleted IS NULL AND email_additional_id = '2' "; 
$res = $DBobject->wrappedSql($sql);
$email_content = unclean($res[0]['email_additional_content']);

//Get "SMS - Trial follow up" message
$sql = "SELECT email_additional_content FROM tbl_email_additional WHERE email_additional_deleted IS NULL AND email_additional_id = '8' ";
$res = $DBobject->wrappedSql($sql);
$sms_content = unclean($res[0]['email_additional_content']);

if(empty($email_content) || empty($sms_content)) sendMail($devAdmin, $from, $fromEmail, "CRON JOB ERROR", "Content message in '$subject' is null.");

try {
	// Get current terms
	$sql = "SELECT * FROM tbl_term WHERE term_deleted IS NULL AND term_published = 1 AND ('{$day}' BETWEEN term_start_date AND term_end_date) ORDER BY term_start_date"; 
	if($terms = $DBobject->wrappedSql($sql)){
		foreach($terms as $t){
			
			// Calculate current week
			$week = $classTermObj->GetCurrentWeekByTermStartDate($t['term_start_date'], $day);
		
			// Get classes associated for the current term 		
			$sql = "SELECT class_object_id, class_name, location_name, agegroup_name, location_street, location_suburb, location_state, location_postcode
			FROM tbl_class 
				LEFT JOIN tbl_classterm ON classterm_class_id = class_object_id 
				LEFT JOIN tbl_location ON location_object_id = class_location_id
				LEFT JOIN tbl_agegroup ON agegroup_id = class_agegroup_id
			WHERE classterm_deleted IS NULL AND classterm_published = '1' AND classterm_term_id = :classterm_term_id 
				AND class_deleted IS NULL AND class_published = '1' 
				AND location_published = '1' AND location_deleted IS NULL AND agegroup_deleted IS NULL 
				AND class_weekday = :class_weekday 
			GROUP BY class_object_id 
			ORDER BY class_object_id";
			$params = array (":classterm_term_id"=>$t['term_id'], ":class_weekday"=>$weekday);
			if($classes = $DBobject->wrappedSql($sql, $params)){	
				foreach($classes as $c){
					echo "<br>==>{$t['term_name']} {$c['class_name']}<br>";
					// Get enrolments/student/user for each class 
					$sql = "SELECT enrolment_id, user_id, user_gname, user_surname, user_email, student_name, student_surname 
						FROM tbl_enrolment 
							LEFT JOIN tbl_student ON student_id = enrolment_student_id 
							LEFT JOIN tbl_user ON user_id = student_user_id 
							LEFT JOIN tbl_payment ON payment_id = enrolment_payment_id 
						WHERE enrolment_deleted IS NULL AND student_deleted IS NULL AND user_deleted IS NULL AND enrolment_published = '1' AND enrolment_type = 'T' 
							AND enrolment_term_object_id = :enrolment_term_object_id AND enrolment_class_object_id = :enrolment_class_object_id
							AND enrolment_week = :enrolment_week AND payment_deleted IS NULL 
						GROUP BY user_email";
					$params = array (":enrolment_term_object_id"=>$t['term_object_id'], ":enrolment_week"=>$week, ":enrolment_class_object_id"=>$c['class_object_id']);
					if($enrolments = $DBobject->wrappedSql($sql, $params)){
						foreach($enrolments as $e){
							// FOREACH MEMBER/PARENT - EMAIL
							if(!in_array($e['user_email'], $membersEmailArr)){
								$membersEmailArr[] = $e['user_email'];
								echo "===>{$e['user_email']} {$e['student_name']} <br>";
								$events['records']["{$t['term_name']}"]["{$t['class_name']}"]["{$e['enrolment_id']}"]['email']= "{$e['user_email']}-{$e['student_name']}";
								$SMARTY->assign('data', $e);
								$SMARTY->assign('dateEmail', $dateEmail);
								$SMARTY->assign('weekday', $weekday);
								$SMARTY->assign('term', $t);
								$SMARTY->assign('class', $c);
								$SMARTY->assign('content', $email_content);
								$body = $SMARTY->fetch('cron/email-trial-followup.tpl');
								createBulkMail(array($e['user_email']), $from, $fromEmail, $subject, $body, 0, array($e['user_id']));
								
								// FOREACH MEMBER/PARENT - SMS
								$sql = "SELECT address_telephone FROM tbl_address WHERE address_deleted IS NULL AND address_user_id = :id ORDER BY address_modified DESC LIMIT 1" ;
								if($address = $DBobject->wrappedSql($sql, array(':id' => $e['user_id']))){
									$temp = preg_replace('/\+|\s|\./', '', $address[0]['address_telephone']);
									$phone = preg_replace('/^04/','614', $temp,1);
									if(!in_array($phone, $membersPhoneArr)){
										if(preg_match("/^614/",$phone)){
											$membersPhoneArr[$e['user_id']] =  $phone;
											$events['records']["{$t['term_name']}"]["{$t['class_name']}"]["{$e['enrolment_id']}"]['sms']= $phone;
										}
									}
								}
							}
						}
					} 
				}
			}
		}
		try {
			print_r($membersPhoneArr);
			sendSMS($membersPhoneArr, $sms_content);
		} catch (Exception $e) {
			$events['error'][] = "Error while running sendSMS: ". $e;
		}
		//echo "<br>=> Emails sent: ". sendBulkMail(); // "cron_email_queue.php" will send them
		
	}
} catch (Exception $e) {
	$events['error'][] = "Error while running".$e;
}

//sendMail($devAdmin, $from, $fromEmail, "CRON JOB - TRIAL FOLLOW-UP $day", json_encode($events));
createBulkMail(array($devAdmin), $from, $fromEmail, "CRON JOB - TRIAL FOLLOW-UP $day", json_encode($events));
echo "<br>=> Cron ended";

